//
//  TMBuyGoodsController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/7/6.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMBuyGoodsController.h"
#import "TMBuyGoodsCell.h"
#import "TMUseDiscountView.h"
#import "TMAccountPayView.h"
#import "TMMyCourseModel.h"
#import "TMNearbyViewModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "TMOrderModel.h"
#import "WXApi.h"
#import "TMScanResultView.h"
@interface TMBuyGoodsController ()<UITableViewDelegate,UITableViewDataSource,WXApiDelegate>
@property (nonatomic, strong) TMUseDiscountView *discountDetailView;
@property (weak, nonatomic) IBOutlet UITableView *listTableview;
@property (weak, nonatomic) IBOutlet UIView *commitView;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (nonatomic, strong) TMAccountPayView *accountPayView;
@property (nonatomic, strong) NSMutableDictionary *param;
@property (nonatomic, strong) NSMutableDictionary *orderParam;
@property (nonatomic, strong) TMNearbyViewModel *viewModel;
@property (nonatomic, strong) NSArray *listArray;
@property (nonatomic, assign) float allMoney;
@property (nonatomic, assign) float allDiscountMoney;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSMutableArray *discountIdArray;
@property (nonatomic, copy) NSString *orderNumber;
@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, strong)TMScanResultView *resultView;
@end

@implementation TMBuyGoodsController
- (void)dealloc{
    NSLog(@"TMBuyGoodsController dealloc");
}
-(NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}
-(NSMutableDictionary *)orderParam
{
    if (!_orderParam) {
        _orderParam = [NSMutableDictionary dictionary];
    }
    return _orderParam;
}
-(NSArray *)listArray{
    if (!_listArray) {
        _listArray = [NSArray array];
    }
    return _listArray;
}
-(NSMutableArray *)allArray{
    if (!_allArray) {
        _allArray = [NSMutableArray array];
    }
    return _allArray;
}
-(NSMutableArray *)discountIdArray{
    if (!_discountIdArray) {
        _discountIdArray = [NSMutableArray array];
    }
    return _discountIdArray;
}
-(TMUseDiscountView*)discountDetailView{
    if (_discountDetailView == nil) {
        _discountDetailView = [[NSBundle mainBundle] loadNibNamed:@"TMDiscountDetailView" owner:self options:nil][2];
    }
    return _discountDetailView;
}
-(TMAccountPayView*)accountPayView{
    if (_accountPayView == nil) {
        _accountPayView = [[NSBundle mainBundle] loadNibNamed:@"TMDiscountDetailView" owner:self options:nil][1];
    }
    return _accountPayView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单信息";
    self.viewModel = [[TMNearbyViewModel alloc]init];
    [self.listTableview registerNib:[UINib nibWithNibName:@"TMBuyGoodsCell" bundle:nil] forCellReuseIdentifier:@"TMBuyGoodsCell"];
    self.listTableview.tableFooterView = [UIView new];
    self.listTableview.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"#FAFAFA"];
    self.listTableview.delegate = self;
    self.listTableview.dataSource = self;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goTopay)];
    [self.commitView addGestureRecognizer:tap];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess:) name:@"ZLAliReturnSucceedPayNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFailed:) name:@"ZLAliReturnFailedPayNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(useResult:) name:@"USEDISCOUNTNOTI" object:nil];
//    self.listTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.viewModel getBuyCourseWith:@{@"id":[SPToolSet arrayToJSONString:self.listDic]} Success:^(id responseObject) {
            self.listArray = responseObject;
            double money = 0.0;
            for (TMMyCartModel *model in self.listArray) {
                money = money + model.all_money;
                TMOrderModel *order = [[TMOrderModel alloc]initWithPrice:0 AndFactprice:model.price AndCoup_money:0 AndCoup_id:0 AndCid:[self.listDic[[self.listArray indexOfObject:model]] integerValue] AndSid:model.sid AndIndex:0 AndCar:[self.caridArray[[self.listArray indexOfObject:model]] integerValue]];
                [self.allArray addObject:[NSString stringWithFormat:@"%.02f",model.all_money]];
                [self.discountIdArray addObject:order];
            }
            self.totalLabel.text = [NSString stringWithFormat:@"合计：%.02f", money];
            [self.listTableview reloadData];
           // [self.listTableview.mj_header endRefreshing];
        } failed:^(NSString *error) {
            [self.listTableview reloadData];
            //[self.listTableview.mj_header endRefreshing];
//        }];
    }];
    //[self.listTableview.mj_header beginRefreshing];
}

- (void)paySuccess:(NSNotification *)noti{
    if (self.accountPayView) {
        [self.accountPayView removeFromSuperview];
    }
    [TMProgressHUD showSuccessWithStyleDarkStatus:@"支付成功"];
    [self displayResultView];
}
- (void)gotoHome{
    TMBaseTabbarContriller *rootTabbar = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TMBaseTabbarContriller"];
    rootTabbar.selectedIndex = 3;
    [UIApplication sharedApplication].keyWindow.rootViewController = rootTabbar;
}
- (void)payFailed:(NSNotification *)noti{
    [TMProgressHUD showErrorWithStyleDarkStatus:@"支付失败！"];
    if (self.accountPayView) {
        [self.accountPayView removeFromSuperview];
    }
}
- (void)useResult:(NSNotification *)noti{
    
    TMMyCartModel *model = self.listArray[self.selectIndex];
    [self.viewModel getRealUseDiscountWith:@{@"id":@([noti.userInfo[@"usid"]integerValue]),@"cid":@(model.coid),@"uid":@([TMUserManager deaufatManager].userModel.uid),@"token":[TMUserManager deaufatManager].userModel.token} Success:^(id responseObject) {
        if (self.discountDetailView) {
            [self.discountDetailView removeFromSuperview];
        }
        TMOrderModel *or = self.discountIdArray[self.selectIndex];
        or.coup_id = [noti.userInfo[@"usid"] integerValue];
        or.coup_money = [noti.userInfo[@"price"]doubleValue];
        or.price = [responseObject[@"money"] doubleValue];
        for(TMMyCartModel * models in self.listArray){
            if (models == model) {
               models.nowMoney = [responseObject[@"money"] doubleValue];
            }
        }
        [self.allArray replaceObjectAtIndex:self.selectIndex withObject:[NSString stringWithFormat:@"%.02f", [responseObject[@"money"] doubleValue]]];
        double money = 0.0;
//        for (TMMyCartModel *model in self.listArray) {
//            money = money + model.all_money;
//        }
        for (NSString *aa in self.allArray) {
            money = money + [aa doubleValue];
        }
        self.totalLabel.text = [NSString stringWithFormat:@"合计：%.02f",money];
        [self.listTableview reloadData];
        
    } failed:^(NSString *error) {
        
    }];
    
}
#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TMBuyGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMBuyGoodsCell" forIndexPath:indexPath];
    cell.orderModel = self.listArray[indexPath.row];
    TMMyCartModel *model = self.listArray[indexPath.row];
    //使用优惠券
    __weak typeof(self) weakSelf =  self;
    cell.disBlock = ^{
        if (weakSelf.discountDetailView) {
            [weakSelf.discountDetailView removeFromSuperview];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"begainToUse" object:nil];
        [weakSelf discountDetailView];
        weakSelf.selectIndex = indexPath.row;
        weakSelf.discountDetailView.cid = model.coid;
       weakSelf.discountDetailView.type = WhereDiscountGet;
        weakSelf.discountDetailView.frame = CGRectMake(0, 0, weakSelf.navigationController.view.bounds.size.width, weakSelf.navigationController.view.bounds.size.height);
        [weakSelf.navigationController.view addSubview:weakSelf.discountDetailView];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return 179;
}
//提交订单。
- (void)goTopay{

    double money = 0.0;
    for (NSString *aa in self.allArray) {
        money = money + [aa doubleValue];
    }
    [self.orderParam setValue:[TMUserManager deaufatManager].userModel.token forKey:@"token"];
    [self.orderParam setValue:@([TMUserManager deaufatManager].userModel.uid) forKey:@"uid"];
    [self.orderParam setValue:@(money) forKey:@"all_money"];
    NSMutableArray *arr = [NSMutableArray array];
    NSMutableArray *caridA = [NSMutableArray array];
    for (TMOrderModel *oder in self.discountIdArray) {
        if (oder.price != oder.fact_price - oder.coup_money) {
            oder.price = oder.fact_price;
        }
        NSDictionary *orderList = @{@"price":@(oder.price),@"fact_price":@(oder.fact_price),@"coup_money":@(oder.coup_money),@"cid":@(oder.cid),@"sid":@(oder.sid),@"coup_id":@(oder.coup_id)};
        [arr addObject:orderList];
        if (self.isFromBuy == NO) {
            [caridA addObject:[NSString stringWithFormat:@"%ld", oder.carid]];
        }else{
            if ([caridA containsObject:[NSString stringWithFormat:@"%ld", oder.carid]]) {
                [caridA removeObject:[NSString stringWithFormat:@"%ld", oder.carid]];
            }
        }
    }
    [self.orderParam setValue:[SPToolSet arrayToJSONString:arr] forKey:@"order"];
    if (self.isFromBuy == NO) {
        [self.orderParam setValue:[SPToolSet arrayToJSONString:caridA] forKey:@"car_id"];
    }
    [self.viewModel CommitOrderWith:self.orderParam Success:^(id responseObject) {
        self.orderNumber = responseObject[@"number"];
        [self reallyToPay:money];
    } failed:^(NSString *error) {
        
    }];
}
- (void)reallyToPay:(float)all{
    _accountPayView = [[NSBundle mainBundle] loadNibNamed:@"TMDiscountDetailView" owner:self options:nil][1];
    _accountPayView.frame = CGRectMake(0, 0, self.navigationController.view.bounds.size.width, self.navigationController.view.bounds.size.height);
    [self.navigationController.view addSubview:_accountPayView];
    _accountPayView.bankLabel.text = [NSString stringWithFormat:@"所需支付:%.02f",all];
    __weak typeof(self) weakself = self;
    _accountPayView.block = ^(NSInteger code) {
//        if (code == 2) {
            [weakself.param setValue:@(code) forKey:@"type"];
            [weakself.param setValue:[TMUserManager deaufatManager].userModel.token forKey:@"token"];
            [weakself.param setValue:@([TMUserManager deaufatManager].userModel.uid) forKey:@"uid"];
            [weakself.param setValue:weakself.orderNumber forKey:@"number"];
            [weakself.param setValue:@(all) forKey:@"money"];
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
            [securityPolicy setAllowInvalidCertificates:YES];
            [manager setSecurityPolicy:securityPolicy];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];//,@"application/json"
            [manager POST:@"http://app.yxp123.com/home/pays/to_pay" parameters:weakself.param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            } progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@", string);
                if (code == 2) {
                    NSString *appScheme = @"yxpyhd";
                    [[AlipaySDK defaultService] payOrder:string fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                        NSLog(@"reslut = %@",resultDic);
                    }];
                }else{
//                    {"appid":"wx9bd061b8f82368af","partnerid":"1510892881","prepayid":"wx0318300949253521f507dddc0713511872","timestamp":"1535970609","noncestr":"RJg2Npdi08AG4Lkf","package":"Sign=WXPay","sign":"E4AF2848592F0661888CE1788CA04E4C"}
                    //调起微信支付
                    PayReq* req             = [[PayReq alloc] init];
                    req.openID              = [dic objectForKey:@"appid"];
                    req.partnerId           = [dic objectForKey:@"partnerid"];
                    req.prepayId            = [dic objectForKey:@"prepayid"];
                    req.nonceStr            = [dic objectForKey:@"noncestr"];
                    req.timeStamp           = [[dic objectForKey:@"timestamp"] intValue];
                    req.package             = [dic objectForKey:@"package"];
                    req.sign                = [dic objectForKey:@"sign"];
                    [WXApi sendReq:req];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"error%@", error);
                
            }];
//        }else{
//
//        }
    };
}

- (void)displayResultView{
    self.resultView = [[NSBundle mainBundle] loadNibNamed:@"TMScanResultView" owner:self options:nil].lastObject;
    [self.navigationController.view addSubview:self.resultView];
    self.resultView.frame = CGRectMake(0, 0, kWindowW, kWindowH);
    self.resultView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    __weak typeof(self) safeSelf = self;
    self.resultView.scanBlock = ^{
        [safeSelf gotoHome];
    };
}
@end
